<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>发送ajax 请求</title>
</head>
<body>
<script type="text/javascript">
    window.onload = function (){
        document.getElementById("btn").onclick=function (){
            //1.创建核心对象
            var xhr = new XMLHttpRequest()
            //2.注册回调函数
            xhr.onreadystatechange = function (){
                if(this.readyState == 4){
                    if(this.status == 200){
                        document.getElementById("info").innerHTML = this.responseText
                        //传 xhr.send("username="+username+"&password="+password)
                        //页面显示username=admin&password=123&age=19
                        //传JSON字符串给后端：{"username":"admin","password":"123","age":19}
                    }else {
                        alert(this.status)
                    }
                }
            }
            //3.开启通道
            xhr.open("POST","/springmvc07/testRequestEntity",true)
            //4.发送请求
            // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
            xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8")
            //获取表单数据
            var id = document.getElementById("id").value
            var username = document.getElementById("username").value
            var password = document.getElementById("password").value
            var age = document.getElementById("age").value
            var user = {
                "id" : id,
                "username" : username,
                "password" : password,
                "age" : age
            }
            xhr.send(JSON.stringify(user))
            // xhr.send("username="+username+"&password="+password)
        }
    }
</script>
序号：<input type="text" id="id"><br>
用户名：<input type="text" id="username"><br>
密码：<input type="password" id="password"><br>
年龄：<input type="text" id="age"><br>
<input type="button" value="提交" id="btn"><br>
<span id="info"></span>
</body>
</html>